package 代码记录.指定公司代码练习记录.华为_2024.分值200;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @author zx
 * @create 2024-02-16 14:41
 * 暂时不看，属于搜索矩阵类问题，但是这个题的题意和测试用例怪怪的
 */
public class 聚餐地点_1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int x = sc.nextInt();
        int y = sc.nextInt();

        int[][] maze = new int[x][y];
        List<int[]> hwCoords = new ArrayList<>();
        List<int[]> cgCoords = new ArrayList<>();

        for (int i = 0; i < x; i++) {
            for (int j = 0; j < y; j++) {
                maze[i][j] = sc.nextInt();
                if (maze[i][j] == 2) {
                    hwCoords.add(new int[]{i, j});
                } else if (maze[i][j] == 3) {
                    cgCoords.add(new int[]{i, j});
                }
            }
        }

        int[] xh = hwCoords.get(0);
        int[] xw = hwCoords.get(1);
        int res = 0;
        for (int[] guan : cgCoords) {
            int[][] tempMaze = copyMaze(maze);
            int endX = guan[0];
            int endY = guan[1];
            if (canReachEnd(xh[0], xh[1], tempMaze, endX, endY) == 1) {
                tempMaze = copyMaze(maze);
                if (canReachEnd(xw[0], xw[1], tempMaze, endX, endY) == 1) {
                    res++;
                }
            }
        }
        System.out.println(res);
    }

    public static int[][] copyMaze(int[][] maze) {
        int rows = maze.length;
        int cols = maze[0].length;
        int[][] copy = new int[rows][cols];
        for (int i = 0; i < rows; i++) {
            System.arraycopy(maze[i], 0, copy[i], 0, cols);
        }
        return copy;
    }

    public static int canReachEnd(int x, int y, int[][] maze, int endX, int endY) {
        int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

        if (x == endX && y == endY) {
            return 1;
        }

        for (int[] dir : directions) {
            int newX = x + dir[0];
            int newY = y + dir[1];

            if (isValidPosition(newX, newY, maze) && maze[newX][newY] != 1) {
                maze[x][y] = 1;
                if (canReachEnd(newX, newY, maze, endX, endY) == 1) {
                    return 1;
                }
            }
        }

        return 0;
    }

    public static boolean isValidPosition(int x, int y, int[][] maze) {
        int rows = maze.length;
        int cols = maze[0].length;
        return x >= 0 && x < rows && y >= 0 && y < cols;
    }
}
